package com.swuwen.ssh.hibernate;

import com.swuwen.ssh.hiring.entity.ResumeEntity;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * 记录hirbernate配置过程
 */
public class HirbernateDemo {
    /**
     * sessionFactory【数据库连接】
     */
    private SessionFactory sessionFactory;
    /**
     * 某次会话
     */
    private Session session;

    private Transaction transaction;

    /**
     * 加载工厂，完成工厂的初始化
     */
    @Before
    public void init() {
        //加载hibernate.cfg.xml与*.hbm.xml
        Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
        //创建session的工厂
        sessionFactory = configuration.buildSessionFactory();
        //取得session
        session = sessionFactory.openSession();
        //打开事务
        transaction = session.beginTransaction();
    }

    @After
    public void destory() {
        //关闭事务
        transaction.commit();
        //关闭session
        session.close();
        //关闭工厂
        sessionFactory.close();
    }


    /**
     * 数据库获取记录，普通查询
     */
    @Test
    public void get() {
        ResumeEntity entity = session.get(ResumeEntity.class, 1);
        System.out.println(entity);
    }
}